package com.umeox.watch.httpclient.core;



import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class HttpMessage{
    protected byte[] body;
    protected Map<String, List<String>> headers = new HashMap<>();

    public byte[] getBody() {
        return this.body;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }

    public Map<String, List<String>> getHeaders() {
        return this.headers;
    }

    public void setHeaders(Map<String, List<String>> headers) {
        this.headers = headers;
    }

    public void addHeader(String name, String value) {
        name = name.trim().toLowerCase();
        if (this.headers.containsKey(name)) {
            this.headers.get(name).add(value);
        } else {
            List<String> values = new ArrayList<>();
            values.add(value.trim());
            this.headers.put(name, values);
        }
    }

    public String getFirstHeaderValue(String name) {
        return this.headers.containsKey(name) && this.headers.get(name).size() > 0 ? (String) ((List) this.headers.get(name)).get(0) : null;
    }

    public void parse(JSONObject message) {
        JSONObject headers = message.getJSONObject("header");

        for (Map.Entry<String, Object> header : headers.entrySet()) {
            if (header.getValue() instanceof String) {
                this.addHeader(header.getKey(), (String) header.getValue());
            } else if (header.getValue() instanceof List) {
                List<String> values = (List<String>) header.getValue();
                for (String value : values) {
                    this.addHeader(header.getKey(), value);
                }
            }
        }
        this.body = message.getBytes("body");
    }

}
